package com.xinzhitong.www.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.Properties;

/**
 * properties帮助类
 *
 * @author 徐鑫
 */
public class PropertiesHelper {

    public static void getFromPropertiesFile(String path, Object target) {
        Properties properties = new Properties();
        // 使用InPutStream流读取properties文件
        try {
            BufferedReader bufferedReader =
                    new BufferedReader(
                            new InputStreamReader(
                                    Objects.requireNonNull(PropertiesHelper.class
                                            .getClassLoader()
                                            .getResourceAsStream(path))));
            properties.load(bufferedReader);

            //通过反射赋值
            Class c = target.getClass();
            for (Field field : c.getDeclaredFields()) {
                //设置为字段可通过反射访问值
                field.setAccessible(true);
                try {
                    field.set(target, properties.getProperty(field.getName()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
